package com.dalianpai.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dalianpai.common.exception.BizCodeEnume;
import com.dalianpai.common.to.SocialUser;
import com.dalianpai.common.utils.HttpUtils;
import com.dalianpai.common.utils.RRException;
import com.dalianpai.gulimall.member.dao.MemberLevelDao;
import com.dalianpai.gulimall.member.entity.MemberLevelEntity;
import com.dalianpai.gulimall.member.vo.UserLoginVo;
import com.dalianpai.gulimall.member.vo.UserRegistVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dalianpai.common.utils.PageUtils;
import com.dalianpai.common.utils.Query;

import com.dalianpai.gulimall.member.dao.MemberDao;
import com.dalianpai.gulimall.member.entity.MemberEntity;
import com.dalianpai.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(UserRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_Status", "1"));
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if(count > 0){
            throw new RRException(BizCodeEnume.PHONE_EXIST_EXCEPTION.getMessage(),BizCodeEnume.PHONE_EXIST_EXCEPTION.getCode());
        }
        Integer count2 = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", vo.getPhone()));
        if(count2 > 0){
            throw new RRException(BizCodeEnume.USER_EXIST_EXCEPTION.getMessage(),BizCodeEnume.USER_EXIST_EXCEPTION.getCode());
        }

        memberDao.insert(memberEntity);

    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if(entity == null){
            return null;
        }else{
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if(matches){
                return entity;
            }else{
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null){
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }else{
            MemberEntity regist = new MemberEntity();
            try {
                Map<String, String> query = new HashMap<>();
                query.put("access_token",socialUser.getAccess_token());
                query.put("uid",uid);
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if(response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            }catch (Exception e){
            }
                regist.setSocialUid(socialUser.getUid());
                regist.setAccessToken(socialUser.getAccess_token());
                regist.setExpiresIn(socialUser.getExpires_in());
                memberDao.insert(regist);
                return regist;
        }
    }

}